"""Lead AI summary model for CRM-SaaS system."""

from __future__ import annotations

import enum
from typing import TYPE_CHECKING, Any

from sqlalchemy import ForeignKey, Text, JSON, Boolean, Enum as SQLEnum
from sqlalchemy.orm import Mapped, mapped_column, relationship

from ..db.base_class import Base
from ..models.base import TimestampMixin

if TYPE_CHECKING:
    from ..models.lead import Lead
    from ..models.user import User


class AIProvider(str, enum.Enum):
    """AI service providers."""

    QWEN3 = "qwen3"


class LeadAISummary(Base, TimestampMixin):
    """AI-generated lead summary."""

    __tablename__ = "leadaisummary"
    id: Mapped[int] = mapped_column(primary_key=True, index=True)
    provider: Mapped[AIProvider] = mapped_column(
        SQLEnum(AIProvider), nullable=False, default=AIProvider.QWEN3
    )
    keywords: Mapped[list[str] | None] = mapped_column(JSON, nullable=True)
    pain_points: Mapped[list[str] | None] = mapped_column(JSON, nullable=True)
    suggested_actions: Mapped[list[str] | None] = mapped_column(JSON, nullable=True)
    contacts_highlight: Mapped[dict[str, Any] | None] = mapped_column(JSON, nullable=True)
    raw_prompt: Mapped[str] = mapped_column(Text, nullable=False, comment="Audit trail")
    raw_response: Mapped[str] = mapped_column(Text, nullable=False, comment="Audit trail")
    reviewed: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)

    # Foreign keys
    lead_id: Mapped[int] = mapped_column(ForeignKey("leads.id"), nullable=False, index=True)
    reviewer_id: Mapped[int | None] = mapped_column(
        ForeignKey("users.id"), nullable=True, index=True
    )

    # Relationships
    lead: Mapped[Lead] = relationship("Lead", back_populates="ai_summaries")
    reviewer: Mapped[User | None] = relationship("User")
